package player

import (
	"base"
	"emma/deep"
	"fmt"
	"game_server/logic/db/api"
	. "game_server/logic/internal"
	"game_server/model"
	"proto/base"
)

type playerCommand struct {
}

func init() {
	Skeleton.AfterInit(func() {
		command := new(playerCommand)
		Skeleton.RegisterCommand("player.remove", "remove player, input player_id", command.remove)
		Skeleton.RegisterCommand("player.reload", "reload player data, input player_id", command.reload)
	})
}

func (*playerCommand) remove(args []interface{}) interface{} {
	if len(args) < 1 {
		return "not player id"
	}

	playerId := base.PlayerId(args[0].(string))
	player, exists := system.Get(playerId)
	if !exists {
		return fmt.Sprintf("player: %s not exists", playerId)
	}

	rpc.OnLogout(player, proto_base.LogoutReason_Kick)

	system.remove(player)

	return ""
}

func (*playerCommand) reload(args []interface{}) (result interface{}) {
	if len(args) < 1 {
		return "not player id"
	}

	playerId := base.PlayerId(args[0].(string))
	player, exists := system.Get(playerId)
	if !exists {
		return fmt.Sprintf("player: %s not exists", playerId)
	}

	copies := deep.Clone(player).(*model.Player)
	copies.SetId(player.Id())
	if dirtyMark := player.ResetDirtyMark(); dirtyMark.Any() {
		db_api.Save(copies, dirtyMark)
	}

	if !db_api.Load(copies) {
		return "reload failed"
	}
	deep.Copy(player, copies)

	return ""
}
